package com.lifeng.sso.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lifeng.sso.domain.User;

@RequestMapping("/user")
@Controller
public class LoginController {
	public static List<User> users = new ArrayList<User>();
	/*
	 * 模拟数据库查询数据
	 * */
	static{
		User user1 = new User("1","zhangs","123");
		User user2 = new User("2","lis","123");
		User user3 = new User("3","wangw","123");
		users.add(user1);
		users.add(user2);
		users.add(user3);
	}
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request,HttpServletResponse response,
			User userVo,String url,Model model) throws IOException{
		String username = userVo.getUsername();
		String userpwd = userVo.getUserpwd();
		User user = getFindByUserNamePwd(username, userpwd);
		if(user != null){
			request.getSession().setAttribute("user", user);
			if(!StringUtils.isEmpty(url)){
				return "redirect:"+url;
			}else{
				model.addAttribute("msg", "登录成功");
				return "/result.jsp";
			}
		}
		model.addAttribute("msg", "用户名或密码不正确");
		return "/result.jsp";
	}
	
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response,
			User userVo,String url,Model model) throws Exception{
		request.getSession().removeAttribute("user");
		model.addAttribute("msg", "退出登录成功");
		return "/result.jsp";
	}
	
	@RequestMapping("/loginUI")
	public String loginUI(HttpServletRequest request,HttpServletResponse response,
			User userVo,String url,Model model) throws IOException{
		model.addAttribute("url", url);
		return "/login.jsp";
	}
	
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response,
			User userVo,String url,Model model) throws IOException{
		model.addAttribute("msg", "欢迎访问主页");
		return "/result.jsp";
	}
	public static User getFindByUserNamePwd(String username,String userpwd){
		for(User user:users){
			String username1 = user.getUsername();
			String userpwd1 = user.getUserpwd();
			if(username1.equals(username) && userpwd.equals(userpwd1)){
				return user;
			}
		}
		return null;
	}
}
